package cn.gedobu.some.bio;

import org.apache.commons.io.FileUtils;
import org.beryx.textio.TextIO;
import org.beryx.textio.TextIoFactory;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class CLI {
    TextIO cli = TextIoFactory.getTextIO();
    String dlDir = System.getProperty("user.home")+"/.some.bio/dl/";

    public static void main(String[] args)
    {
        CLI console = new CLI();
        console.cli.getTextTerminal().setBookmark("Demo");

        while ( true ) {
            String cmd = console.cli.newStringInputReader()
                    .read("\n> ");

            String[] segments = cmd.split(" ");

            switch ( segments[0] ) {
                case "install":
                    console.install(segments[1]);
                    break;
                case "ls":
                    console.ls();
                    break;
                case "q":
                    console.cli.dispose(null);
                    System.exit(0);
                    break;
                default:
                    console.log(cmd);
            }
        }
    }

    void log(String str) {
        cli.getTextTerminal().print(str+"\n");
    }

    void install(String pkg) {
        log(String.format("Installing %s ...", pkg));
        String savePath = dlDir+pkg;
        File saveDir = mkdir(savePath);
        String url = "https://reactome.org/ContentService/data/query/"+pkg;
        log("正在尝试打开："+url);
        try {
            URL jsonURL = new URL(url);
            File jsonFile = new File(savePath+"/data.query.json");
            FileUtils.copyURLToFile(jsonURL, jsonFile);
            log("下载成功");
            String jsonStr = FileUtils.readFileToString(jsonFile, "UTF-8");
            JSONObject json = new JSONObject(jsonStr);
//            FileUtils.writeStringToFile(jsonFile, json.toString(4), "UTF-8");

            GeneratePojos generator = new GeneratePojos("cn.gedobu.some");
            generator.generateFromJson("REntity", json.toString(), false, false, saveDir);

            log("类文件生成成功");

            String name = json.getString("displayName");
            log(name+" 安装成功！");
        }
        catch (MalformedURLException e) {
            log(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log(e.getMessage());
            e.printStackTrace();
        }
    }

    File mkdir(String directory) {
        File file=new File(directory);
        if(!file.exists()){//如果文件夹不存在
            file.mkdirs();//创建文件夹
        }
        return file;
    }

    void ls() {
        File dlFolder = new File(dlDir);
        if ( dlFolder.isDirectory() ) {
            String[] pkgList = dlFolder.list();
            log("已安装包：");
            for ( String pkg : pkgList ) {
                log(pkg);
            }
        }
    }


}
